import {iMicroTokenInfo} from "@peryl/micro-web";
import {designComponent} from "@peryl/react-compose";
import {Crm} from "./Crm";
import {microApp} from "../microApp";
import {LoginService} from "../common/LoginService";

export const CrmHome = designComponent({
  setup() {

    const init = async (): Promise<iMicroTokenInfo> => {

      if (!microApp.route.state.route) {
        microApp.route.history.push('/public/500');
        const msg = 'Route invalid!';
        throw new Error(msg);
      }

      let { path, query } = microApp.route.state.route;

      const pageRouteConfigMatch = microApp.route.matchPageRoute(path);
      if (!pageRouteConfigMatch) {
        microApp.route.history.push('/public/404');
        const msg = 'No match path of current url!';
        throw new Error(msg);
      }
      /*合并预定义参数、地址查询参数以及动态路由参数*/
      const pageParams = { ...pageRouteConfigMatch.params, ...query, ...pageRouteConfigMatch.routeParams, path };
      if (!query?.token) {
        microApp.route.history.push('/login', { redirect: microApp.route.state.route.fullPath });
        throw new Error("Token invalid, redirect to login!");
      }

      try {
        const tokenInfo = await LoginService.getTokenInfo(query.token);
        microApp.openTab({ path: pageRouteConfigMatch.path, label: pageRouteConfigMatch.title || '', data: pageParams });
        return tokenInfo;
      } catch (e: any) {
        const message = e.message || (typeof e == "string" ? e : JSON.stringify(e));
        microApp.route.history.push('/public/403', { message });
        throw e;
      }
    };

    return () => (
      <Crm init={init}/>
    );
  },
});
